
<!DOCTYPE html>
<html lang="zh-Hans" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>fetch使用的常见问题及解决办法 - 默默默默燃</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="TriDiamond Obsidian,"> 
    <meta name="description" content="一枚前端搬砖队队员的记录册,前言说道fetch就不得不提XMLHttpRequest了，XHR在发送web请求时需要开发者配置相关请求信息和成功后的回调，尽管开发者只关心请求成功后的业务处理，但是也要配置其他繁琐内容，导致配置,"> 
    <meta name="author" content="张白告丶"> 
    <link rel="alternative" href="atom.xml" title="默默默默燃" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">默默默默燃</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="https://zhanghao-web.github.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">fetch使用的常见问题及解决办法</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="javascript:;"><b>「 </b>Article<b> 」</b></a>
                
                July 27, 2018
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2018/07/27/study/fetch%E4%BD%BF%E7%94%A8%E7%9A%84%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98%E5%8F%8A%E8%A7%A3%E5%86%B3%E5%8A%9E%E6%B3%95/" title="fetch使用的常见问题及解决办法" class="">fetch使用的常见问题及解决办法</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    26k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    24 mins.
                </span>
                
                
                
                <span id="busuanzi_container_page_pv">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span id="busuanzi_value_page_pv">0</span>
                </span>
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/Fetch/" rel="tag">Fetch</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>说道fetch就不得不提<code>XMLHttpRequest</code>了，XHR在发送web请求时需要开发者配置相关请求信息和成功后的回调，尽管开发者只关心请求成功后的业务处理，但是也要配置其他繁琐内容，导致配置和调用比较混乱，也不符合关注分离的原则；fetch的出现正是为了解决XHR存在的这些问题。例如下面代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">fetch(url).then(<span class="function"><span class="keyword">function</span>(<span class="params">response</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> response.json();</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(data)</span><br><span class="line">&#125;).catch(<span class="function"><span class="keyword">function</span>(<span class="params">e</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Oops,error"</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>上面这段代码让开发者只关注请求成功后的业务逻辑处理，其他的不用关心，相当简单；也比较符合现代Promise形式，比较友好。</p>
<p>fetch是基于Promise设计的，从上面代码也能看得出来，这就要求fetch要配合Promise一起使用。正是这种设计，fetch所带来的优点正如【传统 Ajax 已死，Fetch 永生总结】的一样：</p>
<ul>
<li><p>语法简单，更加语义化</p>
</li>
<li><p>基于标准的Promise实现，支持async/await</p>
</li>
<li><p>使用isomorphic-fetch可以方便同构</p>
</li>
</ul>
<p>不过话说回来，fetch虽然有很多优点，但是使用fetch来进行项目开发时，也是有一些常见问题的，下面就来说说fetch使用的常见问题。</p>
<h2 id="fetch兼容性"><a href="#fetch兼容性" class="headerlink" title="fetch兼容性"></a>fetch兼容性</h2><p>fetch是相对较新的技术，当然就会存在浏览器兼容性的问题，借用上面应用文章的一幅图加以说明fetch在各种浏览器的原生支持情况：</p>
<p><img src="https://images2015.cnblogs.com/blog/408483/201702/408483-20170221215434991-1565736785.png" alt="fetch兼容性"></p>
<p>从上图可以看出，在各个浏览器低版本的情况下都是不被支持的。</p>
<p>那么问题来了，如何在所有浏览器中通用fetch呢，当然就要考虑fetch的<code>polyfill</code>了。<br><a id="more"></a><br>上面说过，fetch是基于Promise来实现的，所以在低版本浏览器中Promise可能也未被原生支持，所以还需要Promise的polyfill；大多数情况下，实现fetch的polyfill需要涉及到的：</p>
<ul>
<li><strong>promise的polyfill</strong>，例如es6-promise、babel-polyfill提供的promise实现。</li>
<li><strong>fetch的polyfill实现</strong>，例如isomorphic-fetch和whatwg-fetch</li>
</ul>
<p>这样是否就可以安全的使用fetch来进行前后端通信了？上面说了在大多数情况下是这样，但是IE8/9则比较特殊：IE8它使用的是ES3，而IE9则对ES5部分支持。这种情况下还需要ES5的polyfill <code>es5-shim</code>支持了。</p>
<p>上述有关promise的polyfill实现，需要说明的是：</p>
<blockquote>
<p>babel-runtime是不能作为Promise的polyfill的实现的，否则在IE8/9下使用fetch会报Promise未定义。为什么？我想大家猜到了，因为babel-runtime实现的polyfill是局部实现而不是全局实现，fetch底层实现用到Promise就是从全局中去取的，拿不到这报上述错误。</p>
</blockquote>
<p>另外，顺便补充一下fetch的polyfill实现思路是：</p>
<blockquote>
<p>首先判断浏览器是否原生支持fetch，否则结合Promise使用XMLHttpRequest的方式来实现；这正是whatwg-fetch的实现思路，而同构应用中使用的isomorphic-fetch，其客户端fetch的实现是直接require whatwg-fetch来实现的。</p>
</blockquote>
<h2 id="fetch默认不携带cookie"><a href="#fetch默认不携带cookie" class="headerlink" title="fetch默认不携带cookie"></a>fetch默认不携带cookie</h2><p>fetch发送请求默认是不发送cookie的，不管是同域还是跨域；那么问题就来了，对于那些需要权限验证的请求就可能无法正常获取数据，这时可以配置其<code>credentials</code>项，其有3个值：</p>
<ul>
<li>omit: 默认值，忽略cookie的发送</li>
<li>same-origin: 表示cookie只能同域发送，不能跨域发送</li>
<li>include: cookie既可以同域发送，也可以跨域发送</li>
</ul>
<p><code>credentials</code>所表达的含义，其实与XHR2中的<code>withCredentials</code>属性类似，表示请求是否携带cookie；具体可以参考阮一峰老师的<a href="http://www.ruanyifeng.com/blog/2016/04/cors.html" target="_blank" rel="noopener">跨域资源共享 CORS</a> 详解中<code>withCredentials</code>一节的介绍；</p>
<p>这样，若要fetch请求携带cookie信息，只需设置一下credentials选项即可，例如</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fetch(url, &#123;<span class="attr">credentials</span>: <span class="string">'include'</span>&#125;);</span><br></pre></td></tr></table></figure>
<p>另外补充一点：</p>
<blockquote>
<p>fetch默认对服务端通过Set-Cookie头设置的cookie也会忽略，若想选择接受来自服务端的cookie信息，也必须要配置<code>credentials</code>选项；</p>
</blockquote>
<h2 id="fetch请求对某些错误http状态不会reject"><a href="#fetch请求对某些错误http状态不会reject" class="headerlink" title="fetch请求对某些错误http状态不会reject"></a>fetch请求对某些错误http状态不会reject</h2><p>主要是由fetch返回promise导致的，因为fetch返回的promise在某些错误的http状态下如 <strong>400、500</strong>等不会reject，相反它会被resolve；只有网络错误会导致请求不能完成时，fetch 才会被 reject；所以一般会对fetch请求做一层封装，例如下面代码所示：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">checkStatus</span>(<span class="params">response</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (response.status &gt;= <span class="number">200</span> &amp;&amp; response.status &lt; <span class="number">300</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> response;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">const</span> error = <span class="keyword">new</span> <span class="built_in">Error</span>(response.statusText);</span><br><span class="line">  error.response = response;</span><br><span class="line">  <span class="keyword">throw</span> error;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">parseJSON</span>(<span class="params">response</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> response.json();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">request</span>(<span class="params">url, options</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> opt = options||&#123;&#125;;</span><br><span class="line">  <span class="keyword">return</span> fetch(url, &#123;<span class="attr">credentials</span>: <span class="string">'include'</span>, ...opt&#125;)</span><br><span class="line">    .then(checkStatus)</span><br><span class="line">    .then(parseJSON)</span><br><span class="line">    .then(<span class="function">(<span class="params">data</span>) =&gt;</span> ( data ))</span><br><span class="line">    .catch(<span class="function">(<span class="params">err</span>) =&gt;</span> ( err ));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="fetch不支持超时timeout处理"><a href="#fetch不支持超时timeout处理" class="headerlink" title="fetch不支持超时timeout处理"></a>fetch不支持超时timeout处理</h2><p>用过fetch的都知道，fetch不像大多数ajax库那样对请求设置超时timeout，它没有有关请求超时的feature，这一点比较蛋疼。所以在fetch标准添加超时feature之前，都需要polyfill该特性。</p>
<p>实际上，我们真正需要的是<code>abort()</code>, timeout可以通过<code>timeout+abort</code>方式来实现，起到真正超时丢弃当前的请求。</p>
<p>而在目前的fetch指导规范中，fetch并不是一个具体实例，而只是一个方法；<em>其返回的promise实例根据Promise指导规范标准是不能abort的，也不能手动改变promise实例的状态，只能由内部来根据请求结果来改变promise的状态</em>。</p>
<p><strong>既然不能手动控制fetch方法执行后返回的promise实例状态，那么是不是可以创建一个可以手动控制状态的新Promise实例呢</strong>。所以：</p>
<p>实现fetch的timeout功能，其思想就是新创建一个可以手动控制promise状态的实例，根据不同情况来对新promise实例进行resolve或者reject，从而达到实现timeout的功能；</p>
<p>目前可以有两种不同的解决方法：</p>
<ul>
<li>第一种：单纯setTimeout方式</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> oldFetchfn = fetch; <span class="comment">//拦截原始的fetch方法</span></span><br><span class="line"><span class="built_in">window</span>.fetch = <span class="function"><span class="keyword">function</span>(<span class="params">input, opts</span>)</span>&#123;<span class="comment">//定义新的fetch方法，封装原有的fetch方法</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> timeoutId = setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            reject(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">"fetch timeout"</span>))</span><br><span class="line">        &#125;, opts.timeout);</span><br><span class="line">        oldFetchfn(input, opts).then(</span><br><span class="line">            res=&gt;&#123;</span><br><span class="line">                clearTimeout(timeoutId);</span><br><span class="line">                resolve(res)</span><br><span class="line">            &#125;,</span><br><span class="line">            err=&gt;&#123;</span><br><span class="line">                clearTimeout(timeoutId);</span><br><span class="line">                reject(err)</span><br><span class="line">            &#125;</span><br><span class="line">        )</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面方法可以模拟xhr的abort()功能</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> oldFetch = fetch;</span><br><span class="line"><span class="built_in">window</span>.fetch = <span class="function"><span class="keyword">function</span>(<span class="params">input, opts</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> promise(<span class="function"><span class="keyword">function</span>(<span class="params">resolve,reject</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> abort_promise = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            reject(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">"fetch abort"</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">var</span> p = oldFetchfn(input, opts).then(resolve, reject);</span><br><span class="line">        p.abort = abort_promise;</span><br><span class="line">        <span class="keyword">return</span> p;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>方法二：利用Promise.race方法</li>
</ul>
<p>Promise.race方法接受一个promise实例数组参数，表示多个promise实例中任何一个最先改变状态，那么race方法返回的promise实例状态就跟着改变，具体可以参考<a href="http://es6.ruanyifeng.com/#docs/promise#Promise-race" target="_blank" rel="noopener">这里</a>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> oldFetchfn = fetch; <span class="comment">//拦截原始的fetch方法</span></span><br><span class="line"><span class="built_in">window</span>.fetch = <span class="function"><span class="keyword">function</span>(<span class="params">input, opts</span>)</span>&#123;<span class="comment">//定义新的fetch方法，封装原有的fetch方法</span></span><br><span class="line">    <span class="keyword">var</span> fetchPromise = oldFetchfn(input, opts);</span><br><span class="line">    <span class="keyword">var</span> timeoutPromise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>)</span>&#123;</span><br><span class="line">        setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">             reject(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">"fetch timeout"</span>))</span><br><span class="line">        &#125;, opts.timeout)</span><br><span class="line">    &#125;);</span><br><span class="line">    retrun <span class="built_in">Promise</span>.race([fetchPromise, timeoutPromise])</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最后，对fetch的timeout的上述实现方式补充几点：</p>
<ul>
<li><p>timeout不是请求连接超时的含义，它表示请求的response时间，包括请求的连接、服务器处理及服务器响应回来的时间；</p>
</li>
<li><p>fetch的timeout即使超时发生了，本次请求也不会被abort丢弃掉，它在后台仍然会发送到服务器端，只是本次请求的响应内容被丢弃而已；</p>
</li>
</ul>
<h2 id="fetch不支持jsonp"><a href="#fetch不支持jsonp" class="headerlink" title="fetch不支持jsonp"></a>fetch不支持jsonp</h2><p>fetch是与服务器端进行异步交互的，而JSONP是 <strong>外链一个javascript资源，并不是真正ajax</strong>，所以fetch与JSONP没有什么直接关联，当然至少目前是不支持JSONP的。</p>
<p>这里我们把JSONP与fetch关联在一起有点差强人意，fetch只是一个ajax库，我们不可能使fetch支持JSONP；只是我们要实现一个JSONP，只不过这个JSONP的实现要与fetch的实现类似，即<strong>基于Promise来实现一个JSONP</strong>；而其外在表现给人感觉是fetch支持JSONP一样；</p>
<p>目前比较成熟的开源JSONP实现<a href="https://github.com/camsong/fetch-jsonp" target="_blank" rel="noopener">fetch-jsonp</a>给我们提供了解决方案，想了解可以自行前往。不过再次想唠叨一下其JSONP的实现步骤，因为在本人面试的前端候选人中大部分人对JSONP的实现语焉不详；</p>
<p>使用它非常简单，首先需要用npm安装fetch-jsonp</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install fetch-jsonp --save-dev</span><br></pre></td></tr></table></figure>
<p>然后在像下面一样使用：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">fetchJsonp(fetchJsonp(<span class="string">'/users.jsonp'</span>, &#123;</span><br><span class="line">    timeout: <span class="number">3000</span>,</span><br><span class="line">    jsonpCallback: <span class="string">'custom_callback'</span></span><br><span class="line">  &#125;)</span><br><span class="line">  .then(<span class="function"><span class="keyword">function</span>(<span class="params">response</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> response.json()</span><br><span class="line">  &#125;).catch(<span class="function"><span class="keyword">function</span>(<span class="params">ex</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'parsing failed'</span>, ex)</span><br><span class="line">  &#125;)</span><br></pre></td></tr></table></figure>
<h2 id="fetch不支持progress事件"><a href="#fetch不支持progress事件" class="headerlink" title="fetch不支持progress事件"></a>fetch不支持progress事件</h2><p>XHR是原生支持progress事件的，例如下面代码这样：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest()</span><br><span class="line">xhr.open(<span class="string">'POST'</span>, <span class="string">'/uploads'</span>)</span><br><span class="line">xhr.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line">xhr.onerror = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">updateProgress</span> (<span class="params">event</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (event.lengthComputable) &#123;</span><br><span class="line">    <span class="keyword">var</span> percent = <span class="built_in">Math</span>.round((event.loaded / event.total) * <span class="number">100</span>)</span><br><span class="line">    <span class="built_in">console</span>.log(percent)</span><br><span class="line">  &#125;</span><br><span class="line">xhr.upload.onprogress =updateProgress; <span class="comment">//上传的progress事件</span></span><br><span class="line">xhr.onprogress = updateProgress; <span class="comment">//下载的progress事件</span></span><br><span class="line">&#125;</span><br><span class="line">xhr.send();</span><br></pre></td></tr></table></figure>
<p>但是fetch是不支持有关progress事件的；不过可喜的是，根据fetch的指导规范标准，其内部设计实现了Request和Response类；其中Response封装一些方法和属性，通过Response实例可以访问这些方法和属性，例如<code>response.json()、response.body</code>等等；</p>
<p>值得关注的地方是，<code>response.body</code>是一个可读字节流对象，其实现了一个<code>getRender()</code>方法，其具体作用是：</p>
<blockquote>
<p>getRender()方法用于读取响应的原始字节流，该字节流是可以循环读取的，直至body内容传输完成；</p>
</blockquote>
<p>因此，利用到这点可以模拟出fetch的progress,代码实现如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// fetch() returns a promise that resolves once headers have been received</span></span><br><span class="line">fetch(url).then(<span class="function"><span class="params">response</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// response.body is a readable stream.</span></span><br><span class="line">  <span class="comment">// Calling getReader() gives us exclusive access to the stream's content</span></span><br><span class="line">  <span class="keyword">var</span> reader = response.body.getReader();</span><br><span class="line">  <span class="keyword">var</span> bytesReceived = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// read() returns a promise that resolves when a value has been received</span></span><br><span class="line">  reader.read().then(<span class="function"><span class="keyword">function</span> <span class="title">processResult</span>(<span class="params">result</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// Result objects contain two properties:</span></span><br><span class="line">    <span class="comment">// done  - true if the stream has already given you all its data.</span></span><br><span class="line">    <span class="comment">// value - some data. Always undefined when done is true.</span></span><br><span class="line">    <span class="keyword">if</span> (result.done) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">"Fetch complete"</span>);</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// result.value for fetch streams is a Uint8Array</span></span><br><span class="line">    bytesReceived += result.value.length;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'Received'</span>, bytesReceived, <span class="string">'bytes of data so far'</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Read some more, and call this function again</span></span><br><span class="line">    <span class="keyword">return</span> reader.read().then(processResult);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>另外，github上也有使用<code>Promise+XHR</code>结合的方式实现类fetch的progress效果(当然这跟fetch完全不搭边）可以参考这里，具体代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fetchProgress</span>(<span class="params">url, opts=&#123;&#125;, onProgress</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(funciton(resolve, reject)&#123;</span><br><span class="line">        <span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">        xhr.open(opts.method || <span class="string">'get'</span>, url);</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> key <span class="keyword">in</span> opts.headers || &#123;&#125;)&#123;</span><br><span class="line">            xhr.setRequestHeader(key, opts.headers[key]);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        xhr.onload = <span class="function"><span class="params">e</span> =&gt;</span> resolve(e.target.responseText)</span><br><span class="line">        xhr.onerror = reject;</span><br><span class="line">        <span class="keyword">if</span> (xhr.upload &amp;&amp; onProgress)&#123;</span><br><span class="line">            xhr.upload.onprogress = onProgress; <span class="comment">//上传</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (<span class="string">'onprogerss'</span> <span class="keyword">in</span> xhr &amp;&amp; onProgress)&#123;</span><br><span class="line">            xhr.onprogress = onProgress; <span class="comment">//下载</span></span><br><span class="line">        &#125;</span><br><span class="line">        xhr.send(opts.body)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line">fetchProgress(<span class="string">'/upload'</span>).then(<span class="built_in">console</span>.log)</span><br></pre></td></tr></table></figure>
<h2 id="fetch跨域问题"><a href="#fetch跨域问题" class="headerlink" title="fetch跨域问题"></a>fetch跨域问题</h2><p>既然是ajax库，就不可避免与跨域扯上关系；XHR2是支持跨域请求的，只不过要满足浏览器端支持<code>CORS</code>，服务器通过<code>Access-Control-Allow-Origin</code>来允许指定的源进行跨域，仅此一种方式。</p>
<p>与XHR2一样，fetch也是支持跨域请求的，只不过其跨域请求做法与XHR2一样，<code>需要客户端与服务端支持</code>；另外，fetch还支持一种跨域，不需要服务器支持的形式，具体可以<code>通过其mode的配置项来说明</code>。</p>
<p>fetch的mode配置项有3个值，如下：</p>
<ul>
<li><p>same-origin：该模式是不允许跨域的，它需要遵守同源策略，否则浏览器会返回一个error告知不能跨域；其对应的response type为basic。</p>
</li>
<li><p>cors: 该模式支持跨域请求，顾名思义它是以CORS的形式跨域；当然该模式也可以同域请求不需要后端额外的CORS支持；其对应的response type为cors。</p>
</li>
<li><p>no-cors: 该模式用于跨域请求但是服务器不带CORS响应头，也就是服务端不支持CORS；这也是fetch的特殊跨域请求方式；其对应的response type为opaque。</p>
</li>
</ul>
<p>针对跨域请求，cors模式是常见跨域请求实现，但是fetch自带的<code>no-cors</code>跨域请求模式则较为陌生，该模式有一个比较明显的特点：</p>
<blockquote>
<p>该模式允许浏览器发送本次跨域请求，但是不能访问响应返回的内容，这也是其response type为opaque透明的原因。</p>
</blockquote>
<p>这与<code>&lt;img/&gt;</code>发送的请求类似，只是该模式不能访问响应的内容信息；但是它可以被其他APIs进行处理，例如<code>ServiceWorker</code>。另外，该模式返回的repsonse可以在Cache API中被存储起来以便后续的对它的使用，这点对script、css和图片的CDN资源是非常合适的，因为这些资源响应头中都没有CORS头。</p>
<p>总的来说，fetch的跨域请求是使用CORS方式，需要浏览器和服务端的支持。</p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/chengdu.mp3'></li>
                
                    
            </ul>
            
            
            
    <div id='gitalk-container' class="comment link"
        data-ae='true'
        data-ci='ec894e2b66f752e8b7fb'
        data-cs='3ccc2e92bb350688fe2c2dc2930189b62622bfb1'
        data-r='blog-comments'
        data-o='TriDiamond'
        data-a='TriDiamond'
        data-d='undefined'
    >Comments</div>


            
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="https://res.cloudinary.com/tridiamond/image/upload/v1573019751/TriDiamond_logo_ui_xeublz.jpg" height=300 width=300></img>
                    <p>张白告丶</p>
                    <span>Think like an artist, develop like an artisan</span>
                    <dl>
                        <dd><a href="https://github.com/zhanghao-web" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">149 <p>Articles</p></a></li>
                    <li><a href="/categories">23 <p>Categories</p></a></li>
                    <li><a href="/tags">47 <p>Tags</p></a></li>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#前言"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#fetch兼容性"><span class="toc-number">1.1.</span> <span class="toc-text">fetch兼容性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#fetch默认不携带cookie"><span class="toc-number">1.2.</span> <span class="toc-text">fetch默认不携带cookie</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#fetch请求对某些错误http状态不会reject"><span class="toc-number">1.3.</span> <span class="toc-text">fetch请求对某些错误http状态不会reject</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#fetch不支持超时timeout处理"><span class="toc-number">1.4.</span> <span class="toc-text">fetch不支持超时timeout处理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#fetch不支持jsonp"><span class="toc-number">1.5.</span> <span class="toc-text">fetch不支持jsonp</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#fetch不支持progress事件"><span class="toc-number">1.6.</span> <span class="toc-text">fetch不支持progress事件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#fetch跨域问题"><span class="toc-number">1.7.</span> <span class="toc-text">fetch跨域问题</span></a></li></ol></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
        &copy; 2020
        <span class="gradient-text">
            张白告丶
        </span>.
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>



    
<link rel="stylesheet" href="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.css">

    
<script src="//cdn.bootcss.com/gitalk/1.5.0/gitalk.min.js"></script>



<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>



    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="//www.googletagmanager.com/gtag/js?id=UA-149874671-1"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-149874671-1');
    </script>





<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Think like an artist, develop like an artisan", "艺术家思维去思考问题，工匠创造精神去开发"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>




</html>
